//
//  UITextView+Emoticon.swift
//  表情键盘
//
//  Created by cyr on 15/10/26.
//  Copyright © 2015年 cyr. All rights reserved.
//

import UIKit

extension UITextView {
    
    /**
    插入表情符号
    */
    func insertEmoticon(emoticon: YREmoticons) {
        /**
        *  删除文本
        */
        if emoticon.removeEmoticon {
            deleteBackward()
            return
        }
        
        if emoticon.emoji != nil {
            replaceRange(selectedTextRange!, withText: emoticon.emoji!)
        }
        
        /**
        *  表情图片
        */
        if emoticon.chs != nil {
            
            // 创建图片属性字符串
            let attachment = YREmoticonAttachment()
            attachment.chs = emoticon.chs
            attachment.image = UIImage(contentsOfFile: emoticon.imagePath)
            // 设置边界
            let h = font!.lineHeight
            print("线高\(h)")
            attachment.bounds = CGRect(x: 0, y: -4, width: h, height: h)
            
            let imageText = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
            
            // 添加文本字体属性
            imageText.addAttribute(NSFontAttributeName, value: font!, range: NSMakeRange(0, 1))
            
            // 图片文字插入到textView
            let attrString = NSMutableAttributedString(attributedString: attributedText)
            
            attrString.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
            
            let range = selectedRange
            attributedText = attrString
            // 恢复光标位置
            selectedRange = NSRange(location: range.location + 1, length: 0)
        }
        
    }
    
    
    var emoticonText:String {
        
        let attrString = attributedText
        var strM = String()
        attrString.enumerateAttributesInRange(NSMakeRange(0, attrString.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (dict, range, _) -> Void in
            
            if let attachment = dict["NSAttachment"] as? YREmoticonAttachment {
                strM += attachment.chs!
            }else{
                let str = (attrString.string as NSString).substringWithRange(range)
                strM += str
            }
        }
       return strM
    }
    

    
}